<?php
require_once("safefunctions.php");
function handleLogin(&$db) {
	//checks if a session is in progress
	if(!isset($_SESSION["username"])) {
		//set the cookie on the webpage after we logged in
		$userName = trim($_POST["user"]);
		//escape the username to prevent SQL-injects
		$userName = safety($userName);
		//db request to get password
		$pwQuery = mysqli_query($db, "SELECT password FROM users WHERE userName='$userName' LIMIT 1");
		if(!$pwQuery) {
			session_unset();
			session_destroy();
			header("Location: index.php?error=loggedout");
			//send back user here with wrong information
			die("Your browser do not support redirect");
		}
		//get one row from the db-query
		$pw = $pwQuery->fetch_assoc();
		//first element is what we want from query
		$pw = trim($pw["password"]);
		//check if we got a password
		if(!isset($_POST["password"])) {
			session_unset();
			session_destroy();
			header("Location: index.php?error=loggedout");
			//send back user here with wrong information
			die("Your browser do not support redirect");
		}
		//get the password the user tried to login with
		$userPW = $_POST["password"];
		//let us check if the password is correct
		if(!password_verify ($userPW, $pw)) {
			session_unset();
			session_destroy();
			header("Location: index.php?error=true");
			//send back user here with wrong information
			die("Your browser do not support redirect");
		}
		//set session information after successful login
		$_SESSION["username"] = $userName;
	
		//get the name of the user
		$nameQuery = mysqli_query($db, "SELECT id, classId,firstname, lastname, pnr FROM users WHERE userName='".$_SESSION["username"]."' LIMIT 1");
		$name = $nameQuery->fetch_assoc();
		$_SESSION["firstname"] = $name["firstname"];
		$_SESSION["lastname"] = $name["lastname"];
		$_SESSION["pnr"] = $name["pnr"];
		$_SESSION["id"] = $name["id"];
		$_SESSION["classId"] = $name["classId"];
	}
}
?>